<template>
    <div class="login_container">
        <el-dialog class="login_dialog" @close="closeDialog" v-model="userStore.dialogVisible" title="用户登陆" lock-scroll>
            <div class="content">
                <div class="left">
                    <el-form ref="ruleFormRef" v-if="scene" :model="loginParam" :rules="rules">
                        <el-form-item prop="phone">
                            <el-input v-model="loginParam.phone" placeholder="请你输入手机号码" :prefix-icon="User"></el-input>
                        </el-form-item>
                        <el-form-item prop="code">
                            <el-input v-model="loginParam.code" placeholder="请你输入手机验证码" :prefix-icon="Lock"></el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button @click="getCode" size="small" :disabled="!isPhone || flagCode">
                                获取验证码
                                <CountDown v-if="flagCode" :flagCode="flagCode" @getFlagCode="getFlagCode" />
                            </el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button @click="login" class="left_button" type="primary"
                                :disabled="!isPhone || loginParam.code.length !== 6">
                                用户登陆
                            </el-button>
                            <span class="iphoneShow" @click="changeScene">微信扫码登陆</span>
                            <SvgIcon @click="changeScene" class="svgIcon iphoneShow" name="wx" width="24" height="24" />
                        </el-form-item>
                    </el-form>
                    <div v-else>
                        <div id="login_content"></div>
                        <div @click="scene = !scene" class="left_wx-login">
                            <span>手机短信验证码登陆</span>
                            <SvgIcon class="svgIcon" name="iphoneWX" width="24" height="24" />
                        </div>
                    </div>
                </div>
                <div class="right">
                    <div class="top">
                        <div class="imgContent">
                            <img src="../../assets/images/code_app.png" alt="code_app">
                            <SvgIcon name="wx_ash" />
                            <span>微信扫一扫关注</span>
                            <span>"快速预约挂号"</span>
                        </div>
                        <div class="imgContent">
                            <img src="../../assets/images/code_login_wechat.png" alt="code_app">
                            <SvgIcon name="iPhone_ash" />
                            <span>扫一扫下载</span>
                            <span>"预约挂号"APP</span>
                        </div>
                    </div>
                    <div class="bottom">
                        <span>小何官方指定平台</span>
                        <span>快速挂号 安全放心</span>
                    </div>
                </div>
            </div>
        </el-dialog>
    </div>
</template>
<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue';
import { User, Lock } from '@element-plus/icons-vue';
import useUserStore from '@/store/modules/user'
import { reqWxLogin } from '@/api/hospital';
import Throttle from '@/utils/throttle';
import type { WXLoginResponseData } from '@/api/hospital/type';
// 引入倒计时组件
import CountDown from '@/components/countDown/index.vue'
import { useRoute, useRouter } from 'vue-router';
let $route = useRoute();
let $router = useRouter();
// 获取user仓库的数据(visiable)可以控制login组件的对话框显示与隐藏
let userStore = useUserStore()
let scene = ref<boolean>(true);
// 获取form表单实例
let ruleFormRef = ref<any>();
// 收集表单数据
let loginParam = reactive({
    phone: '17720125002',
    code: ''
})
// 控制倒计时组件显示与隐藏
let flagCode = ref<boolean>(false)

// 计算出当前表单元素收集的内容是否为手机格式
let isPhone = computed(() => {
    const reg = /^1((34[0-8])|(8\d{2})|(([35][0-35-9]|4[579]|66|7[35678]|9[1389])\d{1}))\d{7}$/
    return reg.test(loginParam.phone)
})
// 获取验证码按钮的回调
const getCode = async () => {
    // 通知pinia仓库存储验证码
    await userStore.getCode(loginParam.phone).then((resole: any) => {
        console.log(resole);
    }, (reject: any) => {
        console.log(reject);
    })
    flagCode.value = true;
}
// 倒计时为零的时候，通知父组件进行一系列操作
const getFlagCode = (boolean: boolean) => {
    flagCode.value = boolean;
}
// 用户登陆按钮
const login = async () => {
    await ruleFormRef.value.validate(async (valid: any) => {
        if (valid) {
            await userStore.userLogin(loginParam).then(() => {
                userStore.dialogVisible = false;
                // 获取url的query参数
                if ($route.query.redirext) {
                    $router.push($route.query.redirext as string)
                }
            });
        }
    });
}
// 手机自定义校验规则
const validatorPhone = (_: any, value: any, callBack: any) => {
    const reg = /^1((34[0-8])|(8\d{2})|(([35][0-35-9]|4[579]|66|7[35678]|9[1389])\d{1}))\d{7}$/
    if (reg.test(value)) {
        callBack()
    } else {
        callBack(new Error("请输入正确的手机号码"))
    }
}
// 验证码自定义校验规则
const validatorCode = (_: any, value: any, callBack: any) => {
    if (/^\d{6}$/.test(value)) {
        callBack()
    } else {
        callBack(new Error("请输入正确的验证码"))
    }
}
// 表单校验
const rules = reactive({
    phone: [{
        required: true, message: '请输入手机号码', trigger: ['blur', 'change'],
    }, {
        trigger: 'change', validator: validatorPhone
    }],
    code: [{
        required: true, message: '请输入验证码', trigger: ['blur', 'change'],
    }, {
        trigger: 'change', validator: validatorCode
    }]
})
const closeDialog = () => {
    Object.assign(loginParam, {
        phone: '17720125002',
        code: ''
    });
    ruleFormRef.value?.resetFields(['phone', 'code'])
}
const changeScene = async () => {
    scene.value = !scene.value
    // 生成微信扫码登录二维码页面
    // 发请求获取微信扫码二维码需要参数
    // 咱们在想硅谷学校的服务器发请求,获取微信扫码登录页面参数
    // 还需要携带一个参数:告诉学校服务器用户授权成功以后重定向项目某一个页面
    let redirect_URL = encodeURIComponent(window.location.origin + "/wxlogin");
    let { data }: WXLoginResponseData = await reqWxLogin(redirect_URL);
    // 生成微信扫码登录二维码页面
    // @ts-ignore
    new WxLogin({
        self_redirect: true, // true:手机点击确认登录后可以在 iframe 内跳转到 redirect_uri
        id: "login_content", // 显示二维码容器设置
        appid: data.appid, // 应用位置标识appid
        scope: "snsapi_login", // 当前微信扫码登录页面已经授权了
        redirect_uri: data.redirectUri, // 填写授权回调域路径,就是用户授权成功以后，微信服务器向公司后台推送code地址
        state: data.state, // state就是学校服务器重定向的地址携带用户信息
        style: "black",
        href: "",
    });
}

// 监听手机短信验证码盒子回调
watch(() => scene.value, (val) => {
    if (val) {
        userStore.queryState();
    }
})

const hasScene = () => {
    if (window.innerWidth <= 768) {
        scene.value = true
    }
}
// onresize 监听视口变化
window.addEventListener('resize', Throttle(() => {
    hasScene();
}, 400, 0));
</script>
<script lang="ts">
export default {
    name: 'Login'
}
</script>
<style scoped lang="scss">
.login_container {
    :deep(.el-dialog__body) {
        border-top: 1px solid rgb(213, 213, 213);
        border-bottom: 1px solid rgb(213, 213, 213);
    }

    .content {
        display: flex;

        .left {
            width: 50%;
            padding: 20px;
            border: 1px solid rgb(213, 213, 213);

            .left_button {
                width: 100%;
                margin: 0 0 10px !important;
            }

            span,
            .svgIcon {
                cursor: pointer;
                text-align: center;
                margin: 0 auto;
                width: 100%;
            }

            span:hover {
                color: #55affe;
            }

            #login_content {
                display: flex;
                align-items: center;
                justify-content: center;
            }

            .left_wx-login {
                display: flex;
                align-items: center;
                justify-content: center;
                flex-direction: column;
                cursor: pointer;

                span {
                    padding: 12px 0;
                }
            }


        }

        .right {
            padding: 20px;
            width: 50%;

            .top {
                display: flex;
                justify-content: space-between;

                .imgContent {
                    width: 50%;
                    display: flex;
                    flex-direction: column;
                    align-items: center;

                    img {
                        width: 80%;
                    }

                    span {
                        margin: 4px 0;
                    }
                }
            }

            .bottom {
                padding: 16px;
                font-size: 20px;
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;

                span {
                    margin: 6px 0;
                }
            }
        }
    }
}

@media (max-width:1280px) {
    .login_container {
        :deep(.login_dialog) {
            width: 80% !important;
        }
    }
}

@media (max-width:768px) {
    .login_container {
        :deep(.login_dialog) {
            width: 80% !important;
            margin-top: 6vh;
        }

        .content {
            flex-direction: column;
        }

        .left,
        .right {
            padding: 16px !important;
            width: 100% !important;
            border: 1px solid rgb(213, 213, 213);
            padding-bottom: 0 !important;

            .iphoneShow {
                display: none;
            }
        }

        .right {
            margin-top: 10px;
            padding-bottom: 10px !important;

            .bottom {
                display: none !important;
            }
        }
    }

}
</style>